package com.example.mininote;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.text.NumberFormat;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class NoteEditActivity extends Activity {
    private EditText mTitleText;
    private EditText mBodyText;
    private Long mRowId;
    private DiaryDbAdapter mDbHelper;
    private Context mcontext=this;
    double firstNum = 0;// 第一个输入的数据
    char currentSign = '+';// 记录第一次输入的符号
    StringBuffer currentNum = new StringBuffer();// 得到textview中的数据
    boolean isFirstPoint = false;// 第一个数据是否是小数点
    TextView txtResult;// 输出结果
    String histCalc;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDbHelper = new DiaryDbAdapter(this);
        mDbHelper.open();
        setContentView(R.layout.activity_note_edit);

        mTitleText = (EditText) findViewById(R.id.title);
        mBodyText = (EditText) findViewById(R.id.body);
        txtResult = (TextView) findViewById(R.id.txtResult);

        Button confirmButton = (Button) findViewById(R.id.confirm);
        Button deletButton = (Button) findViewById(R.id.delet);

        mRowId = null;

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String title = extras.getString(DiaryDbAdapter.KEY_TITLE);
            String body = extras.getString(DiaryDbAdapter.KEY_BODY);
            mRowId = extras.getLong(DiaryDbAdapter.KEY_ROWID);

            if (title != null) {
                mTitleText.setText(title);
            }
            if (body != null) {
                mBodyText.setText(body);
            }
        }

        confirmButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                String title = mTitleText.getText().toString().trim();
                String body = mBodyText.getText().toString().trim();
                if(!title.equals("")&&!body.equals("")){
                    if (mRowId != null) {
                        mDbHelper.updateDiary(mRowId, title, body);
                    } else
                        mDbHelper.createDiary(title, body);
                    AlertDialog.Builder builder=new AlertDialog.Builder(mcontext);
                    builder.setTitle("提示");
                    builder.setMessage("保存成功");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finish();
                        }
                    });
                    builder.show();

                    Intent mIntent = new Intent();
                    setResult(RESULT_OK, mIntent);

                }
                else{
                    AlertDialog.Builder builder=new AlertDialog.Builder(mcontext);
                    builder.setTitle("提示");
                    builder.setMessage("标题与内容不能为空！");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                }
            }
        });
        deletButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (mRowId != null) {
                    mDbHelper.deleteDiary(mRowId);
                    AlertDialog.Builder builder=new AlertDialog.Builder(mcontext);
                    builder.setTitle("提示");
                    builder.setMessage("删除成功！");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finish();
                        }
                    });
                    builder.show();
                    Intent mIntent = new Intent();
                    setResult(RESULT_OK, mIntent);
                }
            }
        });
    }

    /**
     * 对数据进行初始化
     *
     * @return
     */
    public void init() {
        currentNum.delete(0, currentNum.length());// 设置当前textView中的值为0
        isFirstPoint = false;
    }

    /**
     *将输入的数据转换成double类型
     *
     * @return
     */
    public double stringToDouble() {
        if (currentNum.length() == 0) {// 如果没有输入的数据
            return 0;
        }
        double result = Double.parseDouble(currentNum.toString());
        return result;
    }
    /**
     * 进行计算处理
     * @return
     */
    public double calcu(){
        double result=0;
        switch(currentSign){
            case '+':
                result=firstNum+stringToDouble();
                break;
            case '-':
                result=firstNum-stringToDouble();
                break;
            case '*':
                result=firstNum*stringToDouble();
                break;
            case '/':
                result=firstNum/stringToDouble();
                break;
        }
        //对小数点后的数据进行格式化
        NumberFormat format =NumberFormat.getInstance();
        format.setMaximumFractionDigits(2);
        result=Double.parseDouble(format.format(result));
        return result;
    }
    /**
     * 显示数据
     */
    public void display(){

        txtResult.setText(currentNum.toString());
    }
    /**
     * 处理数据按钮的点击
     *
     * @param view
     */
    public void digital_click(View view) {
        Button btnDigital=(Button) view;
        char text=btnDigital.getText().charAt(0);
        currentNum.append(text);
        display();
    }

    /**
     * 处理加法
     *
     */
    public void add(View view) {
        double result=calcu();
        txtResult.setText(String.valueOf(result));
        firstNum=result;
        currentSign='+';
        init();
    }

    /**
     * 处理减法
     *
     */
    public void sub(View view) {
        double result=calcu();
        txtResult.setText(String.valueOf(result));
        firstNum=result;
        currentSign='-';
        init();
    }

    /**
     * 处理乘法
     *
     */
    public void mul(View view) {
        double result=calcu();
        txtResult.setText(String.valueOf(result));
        firstNum=result;
        currentSign='*';
        init();
    }

    /**
     * 处理除法
     *
     */
    public void div(View view) {
        double result=calcu();
        txtResult.setText(String.valueOf(result));
        firstNum=result;
        currentSign='/';
        init();
    }

    /**
     * 处理等于
     *
     */
    public void equ(View view) {
        double result=calcu();
        histCalc = firstNum+""+currentSign+currentNum.toString();
        txtResult.setText(String.valueOf(result));
        firstNum=result;
        currentSign='+';
        init();
        sendBroadcast(result);
    }

    public void insert(View view) {
        ContentValues values = new ContentValues();

        values.put(CalcProvider.NAME,histCalc);

        values.put(CalcProvider.RESULT,txtResult.getText().toString());

        Uri uri = getContentResolver().insert(
                CalcProvider.CONTENT_URI, values);
        Log.d("broad","insert: " + uri.toString() + " histCalc=" + histCalc + " result="+txtResult.getText().toString());
        Toast.makeText(getBaseContext(),
                uri.toString() + " histCalc=" + histCalc + " result="+txtResult.getText().toString(), Toast.LENGTH_LONG).show();

    }

    public void query(View view) {
        String URL = "content://com.example.provider.CalcResult/calcs";

        Uri calcs = Uri.parse(URL);
        Cursor c = managedQuery(calcs, null, null, null, "name");

        if (c.moveToFirst()) {
            do{
                String result =c.getString(c.getColumnIndex(CalcProvider._ID)) +
                        ", " + c.getString(c.getColumnIndex(CalcProvider.NAME)) +
                        ", " + c.getString(c.getColumnIndex(CalcProvider.RESULT));
                Toast.makeText(this, result,
                        Toast.LENGTH_SHORT).show();
                Log.d("broad", "query: " + result);
            } while (c.moveToNext());
        }
    }
    public void clear(View view){
        String URL = "content://com.example.provider.CalcResult/calcs";
        Uri calcs = Uri.parse(URL);
        final int delRows = getContentResolver().delete(
                calcs, null, null);
        Log.d("broad","delete rows: "+ delRows);
    }
    private void sendBroadcast(double result) {
        Intent intent = new Intent();
        intent.setAction("com.example.action.CALC_BROADCAST");
        Log.d("broad", "send calc broad " + result);
        intent.putExtra("result",result);
        sendBroadcast(intent);

    }

    /**
     * 处理小数点
     *
     */
    public void point_click(View view) {
        if(isFirstPoint){//当地一个数据为小数点时程序返回
            return;
        }
        if(currentNum.length()==0){//当没有输入的数据时返回
            return;
        }
        Button btnPoint=(Button)view;
        char text=btnPoint.getText().charAt(0);
        currentNum.append(text);
        isFirstPoint=true;
        display();
    }
    /**
     * 处理删除数据
     */
    public void del(View view){

        if(currentNum.length()>=1)
        {
            currentNum.delete(currentNum.length()-1,currentNum.length());
        }
        if(currentNum.length()==0){

            init();
            display();
        }
        txtResult.setText(currentNum);
    }


}
